<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\translation\providers;

/**
 * 百度翻译提供商
 */
class BaiduTranslateProvider extends AbstractTranslateProvider
{
    protected function validateConfig()
    {
        if (!$this->hasConfig('api_key') || !$this->hasConfig('api_secret')) {
            throw new \Exception('百度翻译需要配置 api_key 和 api_secret');
        }
    }

    public function translate($text, $targetLanguage, $sourceLanguage = 'zh_CN')
    {
        $text = $this->cleanText($text);
        if (empty($text)) {
            return '';
        }

        // 转换语言代码
        $from = $this->convertLanguageCode($sourceLanguage);
        $to   = $this->convertLanguageCode($targetLanguage);

        // 处理长文本
        $chunks  = $this->splitLongText($text, 4000);
        $results = [];

        foreach ($chunks as $chunk) {
            $result    = $this->translateChunk($chunk, $from, $to);
            $results[] = $result;
        }

        $finalResult = implode('', $results);
        $this->logTranslation($text, $finalResult, $targetLanguage, $sourceLanguage, 'baidu');

        return $finalResult;
    }

    private function translateChunk($text, $from, $to)
    {
        $appid = $this->getConfig('api_key');
        $key   = $this->getConfig('api_secret');
        $salt  = rand(10000, 99999);
        $sign  = md5($appid . $text . $salt . $key);

        $params = [
            'q'     => $text,
            'from'  => $from,
            'to'    => $to,
            'appid' => $appid,
            'salt'  => $salt,
            'sign'  => $sign,
        ];

        $url = $this->getConfig('endpoint') . '?' . http_build_query($params);

        try {
            $response = $this->sendRequest($url, [], 'GET');
            $result   = json_decode($response, true);

            if (!$result) {
                throw new \Exception('响应解析失败');
            }

            if (isset($result['error_code'])) {
                throw new \Exception($this->getBaiduErrorMessage($result['error_code']));
            }

            if (!isset($result['trans_result']) || empty($result['trans_result'])) {
                throw new \Exception('翻译结果为空');
            }

            $translations = [];
            foreach ($result['trans_result'] as $item) {
                $translations[] = $item['dst'];
            }

            return implode('', $translations);

        } catch (\Exception $e) {
            $this->handleTranslationError($e->getMessage(), 'baidu');
        }
    }

    private function convertLanguageCode($languageCode)
    {
        $languageMap = [
            'zh_CN' => 'zh',
            'en_US' => 'en',
            'ja_JP' => 'jp',
            'ko_KR' => 'kor',
            'fr_FR' => 'fra',
            'de_DE' => 'de',
            'es_ES' => 'spa',
            'pt_PT' => 'pt',
            'ru_RU' => 'ru',
            'ar_SA' => 'ara',
        ];

        return $languageMap[$languageCode] ?? 'auto';
    }

    private function getBaiduErrorMessage($errorCode)
    {
        $errorMessages = [
            '52001' => 'APP ID 不存在',
            '52002' => '签名错误',
            '52003' => '访问频率受限',
            '52004' => '账户余额不足',
            '52005' => '长query请求频繁',
            '54000' => '必填参数为空',
            '54001' => '签名错误',
            '54003' => '访问频率受限',
            '54004' => '账户余额不足',
            '54005' => '长query请求频繁',
            '58000' => '客户端IP非法',
            '58001' => '译文语言方向不支持',
            '58002' => '服务当前已关闭',
            '90107' => '认证未通过或未生效',
        ];

        return $errorMessages[$errorCode] ?? "未知错误 (错误码: {$errorCode})";
    }

    public function detectLanguage($text)
    {
        $appid = $this->getConfig('api_key');
        $key   = $this->getConfig('api_secret');
        $salt  = rand(10000, 99999);
        $sign  = md5($appid . $text . $salt . $key);

        $params = [
            'q'     => $text,
            'from'  => 'auto',
            'to'    => 'en',
            'appid' => $appid,
            'salt'  => $salt,
            'sign'  => $sign,
        ];

        $url = $this->getConfig('endpoint') . '?' . http_build_query($params);

        try {
            $response = $this->sendRequest($url, [], 'GET');
            $result   = json_decode($response, true);

            if (isset($result['from'])) {
                return $this->convertToBaiduLanguageCode($result['from']);
            }

            return 'zh_CN';

        } catch (\Exception $e) {
            return 'zh_CN';
        }
    }

    private function convertToBaiduLanguageCode($baiduCode)
    {
        $codeMap = [
            'zh'  => 'zh_CN',
            'en'  => 'en_US',
            'jp'  => 'ja_JP',
            'kor' => 'ko_KR',
            'fra' => 'fr_FR',
            'de'  => 'de_DE',
            'spa' => 'es_ES',
            'pt'  => 'pt_PT',
            'ru'  => 'ru_RU',
            'ara' => 'ar_SA',
        ];

        return $codeMap[$baiduCode] ?? 'zh_CN';
    }
}
